﻿using System;
using System.Reflection;
using Common;
using Common.ConfigModel;
using Common.DataModels;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.Extensions.DependencyInjection;

namespace Extensions.Services;

public static class AddFlunetValidation
{
    public static IServiceCollection AddFlunetValidationSetup(this IServiceCollection service, SetupTypesConfig config)
    {
        // 注册fluentValidation 来验证api的输入实现
        service.AddFluentValidationAutoValidation();
        service.AddValidatorsFromAssembly(config.FluentValidationAssembly);
        return service;
    }

    public static IServiceCollection AddFlunetValidationSetup(this IServiceCollection service, Assembly fluentValidationAssembly)
    {
        // 注册fluentValidation 来验证api的输入实现
        ArgumentNullException.ThrowIfNull(service);
        ArgumentNullException.ThrowIfNull(fluentValidationAssembly);
        service.AddFluentValidationAutoValidation();
        service.AddValidatorsFromAssembly(fluentValidationAssembly);
        return service;
    }
    /// <summary>
    /// 从配置文件读取配置
    /// </summary>
    /// <param name="service"></param>
    /// <param name="fluentValidationAssembly"></param>
    /// <returns></returns>
    public static IServiceCollection AddFlunetValidationSetup(this IServiceCollection service)
    {
        // 注册fluentValidation 来验证api的输入实现
        ArgumentNullException.ThrowIfNull(service);
        var config = Appsettings.app<Startup>("Startup");
        if (config==null|| string.IsNullOrWhiteSpace(config.FluentValidation))
        {
            throw new Exception("fluentvalidation 配置有误  请检查配置文件");
        }
        service.AddFluentValidationAutoValidation();
        service.AddValidatorsFromAssembly(Assembly.Load(config.FluentValidation));
        return service;
    }
}